package com.example.myapplication.mgreendao.pojo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.test.greendao.DaoMaster;
import com.test.greendao.DaoSession;

import org.greenrobot.greendao.identityscope.IdentityScopeType;

public class DBManager {
    private static final String DB_NAME = "user_green.db";
    private Context mContext;//上下文
    private static DBManager mDbManager;
    private static MySqlLiteOpenHelper mDevOpenHelper;
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;

    private DBManager(Context context){
        this.mContext = context;
        // 初始化数据库信息
        mDevOpenHelper = new MySqlLiteOpenHelper(context,DB_NAME,null);
        getDaoMaster(context);
        getDaoSession(context);
    }

    public static DBManager getInstance(Context context){
        if (null == mDbManager){
            synchronized (DBManager.class){
                if (null == mDbManager){
                    mDbManager = new DBManager(context);
                }
            }
        }
        return mDbManager;
    }

    /**
     * 获取可读数据库
     * @param context
     * @return
     */
    public static SQLiteDatabase getReadableDatabase(Context context){
        if (null == mDevOpenHelper){
            getInstance(context);
        }
        return mDevOpenHelper.getReadableDatabase();
        //加密
//        return mDevOpenHelper.getEncryptedReadableDb("1111");
    }
    /**
     * 获取可写数据库
     * @param context
     * @return
     */
    public static SQLiteDatabase getWritableDatabase(Context context) {
        if (null == mDevOpenHelper) {
            getInstance(context);
        }
        return mDevOpenHelper.getWritableDatabase();
//        return mDevOpenHelper.getEncryptedWritableDb("1111");
    }

    /**
     * 获取DaoMaster
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context){
        if (null == mDaoMaster){
            synchronized (DBManager.class){
                if (null == mDaoMaster){
                    mDaoMaster = new DaoMaster(getWritableDatabase(context));
                }
            }
        }
        return mDaoMaster;
    }

    /**
     * 获取DaoSession
     * @param context
     * @return
     */
    public static DaoSession getDaoSession(Context context) {
        if (null == mDaoSession) {
            synchronized (DBManager.class) {
                //不设置缓存，频繁修改增加数据可能有问题
                if (mDaoSession == null)
                mDaoSession = getDaoMaster(context).newSession(IdentityScopeType.None);
            }
        }
        return mDaoSession;
    }

}
